﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Utility.TaskSystem
{
	public class CoroutineTask : Task
	{
		IEnumerator<Task> co_func;
		Task curr;

		public CoroutineTask (IEnumerator<Task> co_func)
		{
			if (co_func == null)
			{
				throw new System.ArgumentNullException ();
			}
			this.co_func = co_func;
		}

		//true for update success
		bool UpdateTask ()
		{
			if (curr != null)
			{
				if (curr.Alive)
				{
					curr.Update ();
					return true;
				}
				else
				{
					curr = null;
				}
			}
			return false;
		}

		protected override void OnUpdate ()
		{
			//if curr is null
			if (curr == null)
			{
				//move to next task
				if (co_func.MoveNext ())
				{
					curr = co_func.Current;
					if (curr == null)
					{
						return;
					}
				}
				//end
				else
				{
					Done ();
					return;
				}
			}

			curr.Update ();
			if (!curr.Alive)
			{
				curr = null;
				Update ();
			}
		}


	}
}
